package com.lyEducation.security.config;

import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
@Component(value = "athenticationFailureHandlerImpl")
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      AuthenticationException e)
      throws IOException, ServletException {
    httpServletResponse.setContentType("application/json;charset=utf-8");
    HashMap<String, String> paramMap = new HashMap<>();
    PrintWriter out = httpServletResponse.getWriter();
    paramMap.put("status", "error");
    if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
      paramMap.put("msg", "用户名或密码输入错误，登录失败!");
    } else if (e instanceof DisabledException) {
      paramMap.put("msg", "账户被禁用，登录失败，请联系管理员!");
    } else {
      paramMap.put("msg", "登录失败，" + e.getMessage());
    }
    out.write(JSON.toJSONString(paramMap));
    out.flush();
    out.close();
  }
}
